import React from 'react'
import { Space, Button, Select, Tooltip, Divider, Dropdown, Badge } from 'antd'
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  FormatPainterOutlined,
  SaveOutlined,
  FolderOpenOutlined,
  SettingOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  CopyOutlined,
  ScissorOutlined,
  UndoOutlined,
  RedoOutlined,
  SearchOutlined,
  BugOutlined,
  HistoryOutlined,
} from '@ant-design/icons'
import { useAppSelector } from '@/store'

const { Option } = Select

interface EditorToolbarProps {
  onExecute?: () => void
  onStop?: () => void
  onFormat?: () => void
  onSave?: () => void
  onOpen?: () => void
  onCopy?: () => void
  onCut?: () => void
  onUndo?: () => void
  onRedo?: () => void
  onSearch?: () => void
  onFullscreen?: () => void
  onSettings?: () => void
  onHistory?: () => void
  isExecuting?: boolean
  isFullscreen?: boolean
  canUndo?: boolean
  canRedo?: boolean
  selectedConnection?: string
  connections?: Array<{ id: string; name: string; is_active: boolean }>
  onConnectionChange?: (connectionId: string) => void
  fontSize?: number
  onFontSizeChange?: (size: number) => void
  theme?: string
  onThemeChange?: (theme: string) => void
}

const EditorToolbar: React.FC<EditorToolbarProps> = ({
  onExecute,
  onStop,
  onFormat,
  onSave,
  onOpen,
  onCopy,
  onCut,
  onUndo,
  onRedo,
  onSearch,
  onFullscreen,
  onSettings,
  onHistory,
  isExecuting = false,
  isFullscreen = false,
  canUndo = false,
  canRedo = false,
  selectedConnection,
  connections = [],
  onConnectionChange,
  fontSize = 14,
  onFontSizeChange,
  theme = 'vs',
  onThemeChange,
}) => {
  const { theme: appTheme } = useAppSelector(state => state.ui)

  // 连接状态统计
  const activeConnections = connections.filter(c => c.is_active)
  const connectionOptions = connections.map(conn => ({
    value: conn.id,
    label: (
      <Space>
        <Badge 
          status={conn.is_active ? 'success' : 'error'} 
          text={conn.name}
        />
      </Space>
    ),
  }))

  const fontSizeOptions = [10, 12, 14, 16, 18, 20, 24].map(size => ({
    value: size,
    label: `${size}px`,
  }))

  const themeOptions = [
    { value: 'vs', label: '浅色主题' },
    { value: 'vs-dark', label: '深色主题' },
    { value: 'hc-black', label: '高对比度' },
  ]

  const settingsMenuItems = [
    {
      key: 'font-size',
      label: (
        <div style={{ padding: '4px 0' }}>
          <div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>字体大小</div>
          <Select
            size="small"
            value={fontSize}
            onChange={onFontSizeChange}
            style={{ width: 80 }}
            options={fontSizeOptions}
          />
        </div>
      ),
    },
    {
      key: 'editor-theme',
      label: (
        <div style={{ padding: '4px 0' }}>
          <div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>编辑器主题</div>
          <Select
            size="small"
            value={theme}
            onChange={onThemeChange}
            style={{ width: 120 }}
            options={themeOptions}
          />
        </div>
      ),
    },
    { type: 'divider' },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '编辑器设置',
      onClick: onSettings,
    },
  ]

  const toolbarStyle = {
    padding: '8px 16px',
    background: appTheme === 'dark' ? '#1f1f1f' : '#fafafa',
    borderBottom: `1px solid ${appTheme === 'dark' ? '#303030' : '#f0f0f0'}`,
    borderRadius: '6px 6px 0 0',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexWrap: 'wrap' as const,
    gap: '8px',
  }

  return (
    <div style={toolbarStyle}>
      {/* 左侧操作区 */}
      <Space size="small" wrap>
        {/* 执行控制 */}
        <Space.Compact>
          <Tooltip title={isExecuting ? '停止执行 (Esc)' : '执行SQL (Ctrl+Enter)'}>
            <Button
              type={isExecuting ? 'default' : 'primary'}
              icon={isExecuting ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
              onClick={isExecuting ? onStop : onExecute}
              loading={isExecuting}
              size="small"
            >
              {isExecuting ? '停止' : '执行'}
            </Button>
          </Tooltip>
        </Space.Compact>

        <Divider type="vertical" />

        {/* 编辑操作 */}
        <Space size="small">
          <Tooltip title="格式化 (Ctrl+Shift+F)">
            <Button
              icon={<FormatPainterOutlined />}
              onClick={onFormat}
              size="small"
            />
          </Tooltip>

          <Tooltip title="保存 (Ctrl+S)">
            <Button
              icon={<SaveOutlined />}
              onClick={onSave}
              size="small"
            />
          </Tooltip>

          <Tooltip title="打开文件">
            <Button
              icon={<FolderOpenOutlined />}
              onClick={onOpen}
              size="small"
            />
          </Tooltip>
        </Space>

        <Divider type="vertical" />

        {/* 编辑器操作 */}
        <Space size="small">
          <Tooltip title="撤销 (Ctrl+Z)">
            <Button
              icon={<UndoOutlined />}
              onClick={onUndo}
              disabled={!canUndo}
              size="small"
            />
          </Tooltip>

          <Tooltip title="重做 (Ctrl+Y)">
            <Button
              icon={<RedoOutlined />}
              onClick={onRedo}
              disabled={!canRedo}
              size="small"
            />
          </Tooltip>

          <Tooltip title="复制 (Ctrl+C)">
            <Button
              icon={<CopyOutlined />}
              onClick={onCopy}
              size="small"
            />
          </Tooltip>

          <Tooltip title="剪切 (Ctrl+X)">
            <Button
              icon={<ScissorOutlined />}
              onClick={onCut}
              size="small"
            />
          </Tooltip>

          <Tooltip title="查找替换 (Ctrl+F)">
            <Button
              icon={<SearchOutlined />}
              onClick={onSearch}
              size="small"
            />
          </Tooltip>
        </Space>
      </Space>

      {/* 右侧设置区 */}
      <Space size="small" wrap>
        {/* 连接选择 */}
        {connections.length > 0 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 12, color: '#666' }}>连接:</span>
            <Select
              size="small"
              value={selectedConnection}
              onChange={onConnectionChange}
              placeholder="选择数据库连接"
              style={{ minWidth: 150 }}
              options={connectionOptions}
              status={selectedConnection && !connections.find(c => c.id === selectedConnection)?.is_active ? 'error' : undefined}
            />
            <Tooltip title={`活跃连接: ${activeConnections.length}/${connections.length}`}>
              <Badge 
                count={activeConnections.length} 
                showZero 
                style={{ backgroundColor: activeConnections.length > 0 ? '#52c41a' : '#ff4d4f' }}
              />
            </Tooltip>
          </div>
        )}

        <Divider type="vertical" />

        {/* 工具按钮 */}
        <Space size="small">
          <Tooltip title="执行历史">
            <Button
              icon={<HistoryOutlined />}
              onClick={onHistory}
              size="small"
            />
          </Tooltip>

          <Tooltip title="调试模式">
            <Button
              icon={<BugOutlined />}
              size="small"
              type={process.env.NODE_ENV === 'development' ? 'primary' : 'default'}
            />
          </Tooltip>

          <Tooltip title={isFullscreen ? '退出全屏' : '全屏模式'}>
            <Button
              icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
              onClick={onFullscreen}
              size="small"
            />
          </Tooltip>

          <Dropdown
            menu={{ items: settingsMenuItems }}
            placement="bottomRight"
            trigger={['click']}
          >
            <Button
              icon={<SettingOutlined />}
              size="small"
            />
          </Dropdown>
        </Space>
      </Space>
    </div>
  )
}

export default EditorToolbar